package com.lanzuo.pana.adapter.client.encoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.StandardCharsets;

public class JsonMessageEncoder implements ProtocolEncoder {

    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        if (!(message instanceof String)) {
            return; // 只处理字符串
        }

        String json = (String) message;
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);

        // 分配缓冲区：json长度 + 1字节 \0
        IoBuffer buffer = IoBuffer.allocate(bytes.length + 1);
        buffer.put(bytes);
        buffer.put((byte) 0); // 添加 \0 作为结束符
        buffer.flip(); // 切换为读模式

        out.write(buffer);
    }

    @Override
    public void dispose(IoSession session) throws Exception {
        // 无需资源释放
    }
}
